//实现异步日志缓冲区
#pragma once

#include <iostream>
//#include <util.hpp>
#include <vector>
#include <cassert>

namespace nhylog
{

    #define DEFALT_BUFFER_SIZE (1 * 1024 * 1024)
    #define THRESHOLD_BUFFER_SIZE (80 * 1024 * 1024)
    #define INCREMENT_BUFFER_SIZE (10 * 1024 * 1024)
    class Buffer
    {
    public:
        Buffer() : _buffer(DEFALT_BUFFER_SIZE),_writer_idx(0),_reader_idx(0)
        {

        }


        //向缓冲区写入数据
        void push(const char* data,size_t len)
        {
            //剩余空间不够
            //1、扩容(最高性能)
            //if(len > writeAbleSize()) _buffer.resize(_buffer.size() + len);
            //2、阻塞/返回false
            //if(len > writeAbleSize()) return;
            
            //让外界控制
            ensureEnough(len);

            //1 将数据拷贝到缓冲区 
            std::copy(data,data+len,&_buffer[_writer_idx]);
            //2 将当前写入位置向后偏移
            moveWriter(len);
        }
        //返回可读数据的起始地址
        const char* begin()
        {
            return &_buffer[_reader_idx];
        }

        //返回可写数据的长度
        size_t writeAbleSize()
        {
            //扩容思路，总是可写，只针对固定大小缓冲区提供

            return (_buffer.size() - _writer_idx);
        }
        
        //返回可读数据的长度
        size_t readAbleSize()
        {
            //不是循环缓冲区，不存在空间循环使用的情况
            return _writer_idx - _reader_idx;
        }

        //读写指针向后偏移操作
        void moveReader(size_t len)
        {
            assert(len  <= readAbleSize());
            _reader_idx+=len;
        }

        //重置读写位置，初始化缓冲区
        void reset()
        {
            _reader_idx = 0;
            _writer_idx = 0;
        }
        //实现交换操作
        void swap(Buffer& buffer)
        {
            _buffer.swap(buffer._buffer);
            std::swap(_reader_idx,buffer._reader_idx);
            std::swap(_writer_idx,buffer._writer_idx);
        }

        //判断缓冲区是否为空
        bool empty()
        {
            return (_reader_idx == _writer_idx);
        }
    private:
        //对空间进行扩容操作
        void ensureEnough(size_t len)
        {
            if(len < writeAbleSize()) return;
            size_t new_size = 0;
            if(_buffer.size() < THRESHOLD_BUFFER_SIZE)
            {
                new_size = _buffer.size() * 2 + len;
            }
            else  
            {
                new_size = _buffer.size() + INCREMENT_BUFFER_SIZE + len;
            }

            _buffer.resize(new_size);
        }
        void moveWriter(size_t len)
        {
            assert(len + _writer_idx < _buffer.size());
            _writer_idx += len;
        }
    private:    

        std::vector<char> _buffer;
        size_t _reader_idx;//当前可读数据的指针
        size_t _writer_idx;//当前可写位置的指针
    };
}